package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/authorInfo")
public class AuthorServlet extends HttpServlet {
    private ObjectMapper objectMapper=new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取作者信息
        resp.setContentType("application/json;charset=utf8");
        String para=req.getParameter("blogId");
        if(para==null||"".equals(para)){
            resp.getWriter().write("参数缺失");
        }
        BlogDao blogDao=new BlogDao();
        Blog blog=blogDao.selectOne(Integer.parseInt(para));
        //判断博客是不是存在
        if(blog==null){
            resp.getWriter().write("该博客不存在");
        }
        UserDao userDao=new UserDao();
        User author=userDao.selectById(blog.getAuthorId());
        if(author==null){
            resp.getWriter().write("该博客作者信息不存在");
        }
        //构造成json字符串来返回
        author.setPassword("");
        resp.getWriter().write(objectMapper.writeValueAsString(author));
        System.out.println(author.getUsername());
    }
}
